import {message,} from 'ant-design-vue'
import Axios from "axios"
import * as utils from './utils'
import {getStore, setStore} from './storage'
import $store from '../../store/index';
import $router from '../../router/index';
import {notice} from './notice';
import config from "../../config/config";

import {Login, getCaptcha} from '@/api/user'
import {checkResponse, timeFix} from '@/assets/js/utils'
import router from '@/router';
import store from '@/store';
import {getMenuForUser} from "@/api/menu";

let HOME_PAGE = config.HOME_PAGE;
const currentOrganization = getStore('currentOrganization', true);
if (currentOrganization) {
    HOME_PAGE = HOME_PAGE + '/' + currentOrganization.code;
}
const crossDomain = config.crossDomain;
let axiosConfig = {};
if (crossDomain) {
    axiosConfig.withCredentials = true;
    axiosConfig.crossDomain = true;
}
const $http = Axios.create(axiosConfig);

async function dealDataBeforeLogin(res) {
      let app = {
        $router: router,
        $store: store,
        loginSuccess: function(res, org) {
            let href = window.location.href
            if(href.indexOf('to=jenkins') >= 0) {
                window.location.replace('/#/jenkins?to=jenkins')
                setTimeout(() => {
                    window.close()
                }, 11000)
            } else {
                window.location.replace('/')
            }
        }
    };
    if (res.data) {
        const obj = {
          userInfo: res.data.member,
          tokenList: res.data.tokenList
        };
        let currentOrganization = getStore('currentOrganization', true);
        const organizationList = res.data.organizationList;
        await app.$store.dispatch('SET_LOGGED', obj);
        await app.$store.dispatch('setOrganizationList', organizationList);
        if (!currentOrganization) {
          currentOrganization = organizationList[0];
        } else {
          const has = organizationList.findIndex(item => item.id == currentOrganization.id);
          if (has === -1) {
            currentOrganization = organizationList[0];
          }
        }
        await app.$store.dispatch('setCurrentOrganization', currentOrganization);
        await app.$store.dispatch('GET_MENU').then((res) => {
          // app.loginSuccess(res, currentOrganization);

          //有的时候，此时GET_MENU并没有从服务端获取到menu，所以再重新获取一次
          getMenuForUser().then(res => {
              setStore('menu', res.data);
              app.loginSuccess(res, currentOrganization);
          })
          .catch(err => {
            console.error('err 64', err)
            window.location.replace('/')
          })

        });

      } else {
        app.oauthLoading = false;
        app.$store.dispatch('SET_LOGOUT');
        // app.$router.replace('/login?redirect=' + this.$router.currentRoute.fullPath);
      }
}

var _html = ''
var _reload = 0
var _post = $http.post
$http.post = (a,b,c,d,e,f,g) => {
    if(a.indexOf('teamwork/login') < 0 && a.indexOf('project/index/index') < 0) {
        let href = window.location.href
        if(href.indexOf('?') > 0) {
            let query = href.split('?')[1]
            if(query.indexOf('from=yunwei') >= 0 && query.indexOf('token=') >= 0 && !window._checking_yunwei_token) {
                window._checking_yunwei_token = true
                let token = query.split('token=')[1].split('&')[0].split('\#')[0]
                console.log('token', token)
                fetch('/api/yunwei/checkTeamworkToken',
                    {
                        headers:{
                        'content-type': 'application/json',
                    },
                    method:'POST', body:JSON.stringify({
                        phone:'15924362008',
                        token,
                    })
                })
                .then(resp=>resp.json())
                .then(data => {
                    console.log('data', data)
                    if(data.data.name && data.data.value) {
                        let loginParams = {
                            remember_me: true,
                            mobile: data.data.name,
                            captcha: data.data.value,
                        };
                        if(loginParams.captcha.indexOf('yunwei:') < 0) {
                            loginParams.captcha = 'yunwei:'+loginParams.captcha
                        }
                        loginParams.clientid = getStore('client_id');
                        Login(loginParams).then(res => {
                            console.log('res', res)
                            if (checkResponse(res)) {
                                loginParams.token = res.token;
                                dealDataBeforeLogin(res);
                            } else {
                                alert('无法登录:'+JSON.stringify(res))
                                window.location.replace('/')
                            }
                        }).catch((err) => {
                            console.error('err', err)
                            alert('无法登录:'+err.message)
                            window.location.replace('/')
                        });

                    } else {
                        alert('无法获取token信息')
                        window.location.replace('/')
                    }
                })
                .catch(err => {
                    console.error('err 131', err)
                    alert('无法登录:'+err.message)
                    window.location.replace('/')
                })
            }
        }
    }
    fetch('/index.html').then(res => res.text()).then(html => {
        if(_html && _html != html) {
            if(!_reload) {
                _reload = 1
                notice({title: '网页已经重新发布，5秒后将自动刷新页面'}, 'notice', 'error', 5);
                setTimeout(() => {
                    window.location.reload(true)
                }, 5000)
            }
        }
        _html = html
    })
    return _post(a,b,c,d,e,f,g)
}
// Before request
$http.interceptors.request.use(
    config => {
        //校验网页是否过期
        // fetch('/index.html').then(res => res.text()).then(data => console.log('data', data))

        //正在请求更新token时，其他接口等待
        config.url = utils.getApiUrl(config.url);
        if (config.method === 'post') {
            const querystring = require('querystring');
            config.data = querystring.stringify(config.data);
        }
        let tokenList = getStore('tokenList', true);
        if (tokenList) {
            let accessToken = tokenList.accessToken;
            let tokenType = tokenList.tokenType;
            config.headers.Authorization = `${tokenType} ${accessToken}`;
        }
        let organization = getStore('currentOrganization', true);
        if (organization) {
            config.headers.organizationCode = organization.code;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
// After request
$http.interceptors.response.use(
    response => {
        response = response.data;
        response.code = Number(response.code);
        // if("无权限操作资源"==response.msg){
        //     debugger;
        // }
        switch (response.code) {
            case 200:
                response.msg !== '' && notice(response.msg, 'message', 'success');
                return Promise.resolve(response);
            case 401:
                console.log('before relogin 61', response)
                notice({
                    title: '登录信息失效，请重新登录 ' + response.code,
                    desc: response.msg
                }, 'notice', 'error', 5);
                return Promise.reject(new Error('登录信息失效，请重新登录'))
                // $router.replace('/member/login?redirect=' + $router.currentRoute.fullPath);
                // $store.dispatch('SET_LOGOUT');
                // return Promise.resolve(response);
            case 403:
                notice({
                    title: response.msg !== '' ? response.msg : '无权限操作资源，访问被拒绝',
                }, 'notice', 'error', 5);
                return Promise.reject(new Error(response.msg || '无权限操作资源，访问被拒绝'))
                // return Promise.resolve(response);
            case 4031:
                //无权限操作资源
                notice({
                    title: response.msg !== '' ? response.msg : '无权限操作资源，访问被拒绝',
                }, 'notice', 'error', 5);
                // $router.replace(HOME_PAGE);
                return Promise.reject(new Error(response.msg || '无权限操作资源，访问被拒绝'))
                // return Promise.resolve(response);
            case 4041:
                //资源不存在
                notice({
                    title: response.msg !== '' ? response.msg : '资源不存在',
                }, 'notice', 'warning', 5);
                // $router.replace(HOME_PAGE);
                return Promise.reject(new Error(response.msg || '资源不存在'))
                // return Promise.resolve(response);
        }
        if (response.code === 200) {
            notice({
                title: '请求错误 ' + response.code,
                desc: response.msg
            }, 'notice', 'warning', 5);
            return Promise.reject(new Error(response.msg || '失败'))
            // return Promise.resolve(response);
        } else {
            response.msg !== '' && notice({
                title: response.msg,
            }, 'notice', 'error', 5);
            return Promise.reject(new Error(response.msg || '失败'))
            // return Promise.resolve(response);
        }
        /*if (response.code == 200) {
            response.msg !== '' && notice(response.msg, 'message', 'success');
            return Promise.resolve(response);
        } else if (response.code === 401) {
            // notice('登录超时，请重新登录');
            $router.replace('/member/login?redirect=' + $router.currentRoute.fullPath);
            $store.dispatch('SET_LOGOUT');
            return new Promise(() => {});
        } else if (response.code === 4010) {
            refreshAccessToken(refreshToken).then(res=>{
                console.log(res);
                return new Promise(() => {
                });
            });
        }else if (response.code === 403) {
            // $router.replace('/403');
            //无权限操作资源
            notice({
                title: response.msg !== '' ? response.msg : '无权限操作资源，访问被拒绝',
            }, 'notice', 'error', 5);
            return Promise.reject(response.msg);
            // return new Promise(() => {});
        } else if (response.code === 4031) {
            // $router.replace('/403');
            //无权限操作资源
            notice({
                title: response.msg !== '' ? response.msg : '无权限操作资源，访问被拒绝',
            }, 'notice', 'error', 5);
            $router.replace(HOME_PAGE);
            return Promise.reject(response.msg);
        } else if (response.code <= 400) {
            response.msg !== '' && notice({
                title: response.msg,
            }, 'notice', 'error', 5);
            return Promise.resolve(response);
        } else if (response.code == 404) {
            //资源不存在
            notice({
                title: response.msg !== '' ? response.msg : '资源不存在',
            }, 'notice', 'warning', 5);
            $router.replace(HOME_PAGE);
            return new Promise(() => {
            });
        } else if (response.code < 500) {
            notice({
                title: '请求错误 ' + response.code,
                desc: response.msg
            }, 'notice', 'warning', 5);
            // $router.back();
            return Promise.reject(response);
        } else {
            notice({
                title: '请求错误 ' + response.code,
                desc: '路径：' + self.url + '，' +
                    response.msg || '未知错误，请联系管理员或稍后重试' +
                    '。'
            }, 'notice', 'warning', 5);
            return new Promise(() => {
            });
        }*/
    },
    error => {
        const response = error.response.data;
        console.log(response);
        response.code = Number(response.code);
        message.destroy();
        switch (response.code) {
            default:
                response.msg !== '' && notice({
                    title: response.msg,
                }, 'notice', 'error', 5);
                return Promise.reject(error);
        }
    }
);

export default $http;
